package org.zwy.gradetrack.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.zwy.gradetrack.entity.GraduationRequirementAchievement;
import org.zwy.gradetrack.mapper.GraduationRequirementAchievementMapper;
import org.zwy.gradetrack.service.GraduationRequirementAchievementService;
import org.zwy.gradetrack.vo.GraduationRequirementAchievementVo;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.time.format.DateTimeFormatter;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;

/**
 * 毕业要求达成度Service实现类
 */
@Service
public class GraduationRequirementAchievementServiceImpl extends ServiceImpl<GraduationRequirementAchievementMapper, GraduationRequirementAchievement> implements GraduationRequirementAchievementService {
    
    private static final Logger log = LoggerFactory.getLogger(GraduationRequirementAchievementServiceImpl.class);

    @Override
    public void calculateComprehensiveScore(GraduationRequirementAchievement achievement) {
        // 直接评价权重 0.7
        BigDecimal directScore = achievement.getDirectEvaluation().multiply(new BigDecimal("0.7"));
        
        // 毕业生自评权重 0.1
        BigDecimal selfScore = achievement.getGraduateSelfEval().multiply(new BigDecimal("0.1"));
        
        // 实习单位评价权重 0.1
        BigDecimal internshipScore = achievement.getInternshipEval().multiply(new BigDecimal("0.1"));
        
        // 教师评价权重 0.1
        BigDecimal teacherScore = achievement.getTeacherEval().multiply(new BigDecimal("0.1"));
        
        // 计算综合评价值
        BigDecimal comprehensiveScore = directScore
            .add(selfScore)
            .add(internshipScore)
            .add(teacherScore)
            .setScale(4, RoundingMode.HALF_UP);
            
        // 设置综合评价值
        achievement.setComprehensiveScore(comprehensiveScore);
        
        // 判断是否达成（综合评价值 >= 0.6）
        achievement.setIsAchieved(comprehensiveScore.compareTo(new BigDecimal("0.6")) >= 0);
    }

    @Override
    public List<Integer> getEvaluationYears() {
        return baseMapper.selectEvaluationYears();
    }

    @Override
    public List<GraduationRequirementAchievementVo> getAchievementVos(Integer evaluationYear) {
        return baseMapper.selectAchievementVos(evaluationYear);
    }

    @Override
    public byte[] exportToExcel(Integer evaluationYear) throws IOException {
        // 查询数据
        List<GraduationRequirementAchievementVo> achievements = baseMapper.selectAchievementVos(evaluationYear);
        log.info("导出Excel查询到的达成度数据: {}", achievements);
        if (!achievements.isEmpty()) {
            log.info("第一个达成度数据详情: {}", achievements.get(0));
        }

        try (Workbook workbook = new XSSFWorkbook();
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {

            Sheet sheet = workbook.createSheet("毕业要求达成度");

            // 创建日期样式 (保留，但暂时不用于日期值本身，而是作为格式参考)
            CreationHelper createHelper = workbook.getCreationHelper();
            CellStyle dateCellStyle = workbook.createCellStyle();
            dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));

            // 定义日期时间格式化器
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {
                "指标点名称", "直接评价", "毕业生自评", "实习单位评价", "教师评价", 
                "综合评价值", "是否达成", "评价年份", "创建时间", "更新时间"
            };
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 填充数据
            int rowNum = 1;
            for (GraduationRequirementAchievementVo achievement : achievements) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(achievement.getIndicatorName());
                row.createCell(1).setCellValue(achievement.getDirectEvaluation().doubleValue() * 100);
                row.createCell(2).setCellValue(achievement.getGraduateSelfEval().doubleValue() * 100);
                row.createCell(3).setCellValue(achievement.getInternshipEval().doubleValue() * 100);
                row.createCell(4).setCellValue(achievement.getTeacherEval().doubleValue() * 100);
                row.createCell(5).setCellValue(achievement.getComprehensiveScore().doubleValue() * 100);
                row.createCell(6).setCellValue(achievement.getIsAchieved() ? "已达成" : "未达成");
                row.createCell(7).setCellValue(achievement.getEvaluationYear());
                
                // 处理时间字段，直接写入格式化后的字符串
                Cell createTimeCell = row.createCell(8);
                if (achievement.getCreateTime() != null) {
                    createTimeCell.setCellValue(achievement.getCreateTime().format(formatter));
                    // createTimeCell.setCellStyle(dateCellStyle); // 不再设置日期样式
                }
                
                Cell updateTimeCell = row.createCell(9);
                if (achievement.getUpdateTime() != null) {
                    updateTimeCell.setCellValue(achievement.getUpdateTime().format(formatter));
                    // updateTimeCell.setCellStyle(dateCellStyle); // 不再设置日期样式
                }
            }

            // 在所有数据填充完毕后，自动调整所有列宽以适应内容
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
                
                // 获取自动调整后的宽度
                int currentWidth = sheet.getColumnWidth(i);
                
                // 定义一个最小宽度，防止列太窄
                int minWidth = 20 * 256; // 增加基础最小宽度到20个字符宽度
                
                // 对于日期时间列，设置一个更大的最小宽度
                if (i == 8 || i == 9) { // "创建时间"和"更新时间"列
                    minWidth = 35 * 256; // 增加日期时间列的最小宽度到35个字符宽度
                }
                
                // 如果当前宽度小于最小宽度，则设置为最小宽度
                if (currentWidth < minWidth) {
                    sheet.setColumnWidth(i, minWidth);
                }
                
                // 在最小宽度的基础上再额外增加一些宽度，使得阅读更舒适
                // 2048单位大约是8个字符宽度，可以根据需要调整
                sheet.setColumnWidth(i, sheet.getColumnWidth(i) + 2048); // 额外增加到约8个字符宽度
            }

            // 将工作簿内容写入 ByteArrayOutputStream
            workbook.write(bos);
            return bos.toByteArray();

        } catch (Exception e) {
            log.error("导出Excel时发生错误: {}", e.getMessage(), e);
            throw new IOException("导出Excel失败", e);
        }
    }
}